//
//  ActionBar.m
//  SlashEM
//
//  Created by dirk on 1/6/10.
//  Copyright 2010 Dirk Zimmermann. All rights reserved.
//

//  This file is part of Slash'EM.
//
//  Slash'EM is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, version 2 of the License only.
//
//  Slash'EM is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with Slash'EM.  If not, see <http://www.gnu.org/licenses/>.

#import "ActionBar.h"
#import "UIFactory.h"
#import "Action.h"
#import "MainViewController.h"

@implementation ActionBar

@synthesize actions;

- (id)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
		self.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
		// adjust frame height
		frame.size.height = [UIFactory buttonHeight];
		self.frame = frame;
		controlCache = [[ZObjectCache alloc] init];
    }
    return self;
}

- (void)layoutSubviews {
	[super layoutSubviews];
	float width = self.contentSize.width;
	float parentWidth = self.bounds.size.width;
	if (width < parentWidth) {
		[self setContentOffset:CGPointMake(-(parentWidth-width)/2, 0.0f) animated:NO];
	}
}

- (UIControl *)buttonForAction:(id<Action>)action {
	UIControl *button = [controlCache objectForKey:action];
	if (!button) {
		button = [UIFactory buttonWithTitle:action.title];
		[button addTarget:action action:@selector(invoke:) forControlEvents:UIControlEventTouchUpInside];
		[button addTarget:self action:@selector(actionInvoked:) forControlEvents:UIControlEventTouchUpInside];
		[controlCache setObject:button forKey:action];
	}
	return button;
}

- (void)actionInvoked:(UIControl *)sender {
	[[MainViewController instance] removeActionBar:self];
}

- (void)setActions:(NSArray *)as {
	if (actions != as) {
		[actions release];
	}
	actions = [as retain];
	[self update];
}

- (void)update {
	BOOL empty = self.subviews.count == 0;
	if (actions && actions.count > 0) {
		CGRect frame = CGRectZero;
		for (id<Action> a in actions) {
			UIView *button = [self buttonForAction:a];
			CGSize buttonSize = [button sizeThatFits:self.bounds.size];
			frame.size = buttonSize;
			button.frame = frame;
			frame.origin.x += buttonSize.width;
			if (empty) {
				[self addSubview:button];
			}
		}
		frame.size.width = frame.origin.x;
		self.contentSize = frame.size;
		float width = frame.size.width;
		float parentWidth = self.bounds.size.width;
		if (width < parentWidth) {
			[self setContentOffset:CGPointMake(-(parentWidth-width)/2, 0.0f) animated:YES];
		}
	}
}

- (void)dealloc {
	[actions release];
	[controlCache release];
    [super dealloc];
}

@end
